﻿using Shared.Exceptions;
using Shared.Http.APIResult;
using ApplicationException = Shared.Exceptions.ApplicationException;

namespace WebApi.Middlewares
{
    public class GlobalExceptionHandler
    {
        private readonly RequestDelegate _next;
        //private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;

        public GlobalExceptionHandler(RequestDelegate next)
        {
            _next = next;
            //_logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        /// <summary>
        /// 处理异常信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            ApiResult<string>? response;

            // 判断异常类型
            switch (exception)
            {
                case DomainException domainException://领域层异常
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    response = new ApiResult<string>
                    {
                        Code = ApiStatusCode.InternalServerError,
                        Errors = [new($"{domainException.ErrorCode}_{domainException.Message}")]
                    };
                    break;
                case ApplicationException applicationException://应用层异常
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    response = new ApiResult<string>
                    {
                        Code = ApiStatusCode.InternalServerError,
                        Errors = [new($"{applicationException.ErrorCode}_{applicationException.Message}")]
                    };
                    //记录日志
                    break;
                default:
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    response = new ApiResult<string>
                    {
                        Code = ApiStatusCode.InternalServerError,
                        Errors = [new(null, "服务器内部错误，请联系管理员")]
                    };
                    //记录日志

                    break;
            }

            await context.Response.WriteAsJsonAsync(response);
        }
    }
}
